﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SailHero.Soft.FrameWork.Models;
using UI.Web.SL.Demo.RIAServices.Web;

namespace UI.Web.Silverlight.Demo.Views
{
    public partial class CustomerListView : UserControl
    {
        private IEnumerable<CUSTOMER> _customerList;
        private CustomerDContext _customerDContext = new CustomerDContext();
        private LoadOperation<CUSTOMER> _loadCustomerListOperation; 
        public CustomerListView()
        {
            InitializeComponent();
            WorkBench.AddedCustomer += new WorkBench.AddedCustomerHandler(Load);

            LoadCustomer(null);
        }

        public void Load()
        {
            LoadCustomer(null);
        }

        public IEnumerable<CUSTOMER> CustomerList
        {
            get { return _customerList; }
            set
            {
                _customerList = value;
            }
        }



        public void LoadCustomer(object o)
        {
            _loadCustomerListOperation = _customerDContext.Load(_customerDContext.GetCustomersQuery());
            _loadCustomerListOperation.Completed += new EventHandler(_loadCustomerListOperation_Completed);
        }

        void _loadCustomerListOperation_Completed(object sender, EventArgs e)
        {
            this.CustomerList = _loadCustomerListOperation.Entities;
            this.dataGrid1.ItemsSource = CustomerList;
        }

        private void DeleteCustomer(CUSTOMER customer)
        {
            _customerDContext.CUSTOMERs.Remove(customer);
            _customerDContext.SubmitChanges(DeleteCustomerCompleted, customer);
        }

        private void DeleteCustomerCompleted(SubmitOperation operation)
        {
            if (operation.IsComplete)
            {
                LoadCustomer(null);
                var customer = (CUSTOMER)operation.UserState;
            }
        }
    }
}
